<template>
  <div class="container">
    <el-card class="box-card" shadow="always">
      <el-row :gutter="24">
        <el-col :span="16">
          <el-form inline @submit.native.prevent="search">
            <el-form-item label="搜索">
              <el-input
                v-model="searchForm.queryConditions"
                clearable
                placeholder=""
                prefix-icon="el-icon-search"
                size="medium"
              />
            </el-form-item>
            <el-form-item label="组织">
              <el-select
                v-model="organizationList.organizeName"
                clearable
                placeholder="全部"
                style="width: 150px"
                @change="organizationSelected"
              >
                <el-option
                  v-for="item in organizationList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.organizeName"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button native-type="submit" size="medium" type="primary"
                >搜索</el-button
              >
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="8">
          <el-button icon="el-icon-download" type="primary" class="btn">
            <a download :href="exportUrl"> 导出 </a>
          </el-button>

          <el-button
            class="btn"
            type="primary"
            icon="el-icon-circle-plus-outline"
            @click="addManagerDialog"
            >添加</el-button
          >
          <!-- <el-upload
            class="upload-demo"
            :action="uploadURL"
            :headers="headers"
            :show-file-list="false"
            :on-success="onSuccess"
            :on-error="onError"
          >
            <el-button icon="el-icon-upload2" type="primary"
              >点击上传</el-button
            >
          </el-upload> -->
        </el-col>
      </el-row>
      <div>
        <el-table
          :data="list"
          border
          style="width: 100%"
          v-loading="childListLoading"
          @expand-change="getPurchaserData"
          :expand-row-keys="expands"
          :row-key="getRowKeys"
        >
          <el-table-column type="expand">
            <template slot-scope="scope">
              <!-- 避免报错 -->
              {{ scope.id }}
              <el-table
                :data="childrenPurchaserList"
                class="children-table"
                v-show="childrenContentisShow"
                height="250"
              >
                <el-table-column
                  type="index"
                  label="采购员序号"
                  width="110"
                  align="center"
                ></el-table-column>
                <el-table-column label="头像" width="70" align="center">
                  <template slot-scope="scope">
                    <el-avatar :src="scope.row.avatar"></el-avatar>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="username"
                  label="用户名"
                  align="center"
                ></el-table-column>
                <el-table-column
                  prop="mobilePhone"
                  label="手机号"
                  align="center"
                ></el-table-column>
                <el-table-column label="归属组织" align="center">
                  <template slot-scope="scope">
                    {{ scope.row.organization.organizeName }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="description"
                  label="业务描述"
                  align="center"
                ></el-table-column>
                <el-table-column label="操作" align="center">
                  <template slot-scope="scope">
                    <el-tooltip content="分配到其他管理员名下" placement="top">
                      <el-button
                        type="primary"
                        icon="el-icon-edit"
                        circle
                        @click="selectManagerDialog(scope.row)"
                      />
                    </el-tooltip>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>

          <el-table-column
            type="index"
            width="50"
            label="序号"
            align="center"
          />
          <el-table-column label="头像" width="70" align="center">
            <template slot-scope="scope">
              <el-avatar :src="scope.row.avatar"></el-avatar>
            </template>
          </el-table-column>

          <el-table-column prop="username" label="用户名" align="center" />
          <el-table-column prop="mobilePhone" label="手机号" align="center" />
          <el-table-column label="归属组织" align="center">
            <template slot-scope="scope">
              {{ scope.row.organization.organizeName }}
            </template>
          </el-table-column>
          <el-table-column prop="description" label="业务描述" align="center" />
          <el-table-column label="操作" fixed="right" width="200" center>
            <template slot-scope="scope">
              <el-tooltip content="查看信息" placement="top">
                <el-button
                  icon="el-icon-search"
                  circle
                  @click="showDialog(scope.row)"
                />
              </el-tooltip>
              <el-tooltip content="编辑信息" placement="top">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  circle
                  @click="editManagerDialog(scope.row)"
                />
              </el-tooltip>
              <el-tooltip content="还原最初密码" placement="top">
                <el-button
                  type="warning"
                  icon="el-icon-refresh"
                  circle
                  @click="refreshPassword(scope.row.id)"
                />
              </el-tooltip>
              <el-tooltip content="删除管理员" placement="top">
                <el-button
                  el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="deleteManager(scope.row)"
                />
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          :current-page="paging.current"
          :page-sizes="paging.pageSizes"
          :page-size="paging.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="paging.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <Dialog
        :visible="managerInfoVisible"
        :info="managerInfo"
        @cancel="cancel"
      />
      <edit-dialog
        :index="index"
        :organization-list="organizationList"
        :title="dialogTitle"
        :visible="editDialogVisible"
        :manager-info="managerInfo"
        @cancel="cancel"
        @ok="ok"
      />
      <ReSelectDialog
        :title="dialogTitle"
        :select-manager="selectManager"
        :visible="selectDialogVisible"
        @cancel="cancelSelect"
        @ok="reSelect"
      />
    </el-card>
  </div>
</template>

<script>
// import { getToken } from "@/utils/auth";
import {
  getAllManagerInfoByPageAndConditions,
  deleteManagerInfo,
  addManagerInfo,
  updateManagerInfo,
} from "@/api/account.js";
import {
  getAllPurchasersByPage,
  updatePurchaserManager,
} from "@/api/purchaser.js";
import { resetPassword } from "@/api/common";
import { getAllOrganizationInfos } from "@/api/organization";
import Dialog from "./components/Dialog";
import EditDialog from "./components/editDialog";
import ReSelectDialog from "./components/reselectDialog";

export default {
  name: "AccountManage",
  components: { Dialog, EditDialog, ReSelectDialog },
  data() {
    return {
      searchForm: {
        queryConditions: "",
        organizeId: "",
      },
      organizationList: [],
      list: [],
      childrenPurchaserList: [],
      paging: {
        total: 0,
        current: 1,
        pageSizes: [5, 10, 15],
        size: 5,
      },
      managerInfoVisible: false,
      managerInfo: {},
      editDialogVisible: false,
      dialogTitle: "",
      index: 0, // 0 添加；1 编辑；2 查看信息
      // headers: {
      //   Authorization: getToken(),
      // },
      childrenContentisShow: false,
      expands: [], // 设置row只展示一行
      selectDialogVisible: false,
      childListLoading: false,
      selectManager: {
        username: "",
        managerId: "",
        purchaserId: "",
      },
    };
  },
  computed: {
    exportUrl() {
      return process.env.VUE_APP_BASE_API + "/superManager/exportManagerExcel";
    },
  },
  created() {
    this.childListLoading = true;
    this.getData();
    this.getOrganizations();
    // console.log(getToken())
  },
  methods: {
    // 获取每一行的id
    getRowKeys(row) {
      return row.id;
    },
    async getOrganizations() {
      const result = await getAllOrganizationInfos();
      this.organizationList = result.data;
      // console.log('@@@@',this.organizationList)
    },
    search() {
      this.paging.current = 1;
      this.childListLoading = true;
      this.getData();
    },
    getData() {
      const form = {
        ...this.searchForm,
        page: this.paging.current,
        pageSize: this.paging.size,
      };
      getAllManagerInfoByPageAndConditions(form)
        .then(({ data }) => {
          console.log(data);
          this.list = data.managerInfos;
          //this.paging.size = data.size
          this.paging.total = data.totalCount;
          this.childListLoading = false;
        })
        .catch((err) => {
          // 如果没有数据就显示为空
          this.list = [];
          // 返还每页显示的条数
          //this.paging.size = res.data.size;
          this.paging.total = 0;
          this.childListLoading = false;
        });
    },
    getPurchaserData(row, expandedRows) {
      console.log("@@@@rowData", row);
      console.log("@@@@rowData", expandedRows);
      let that = this;
      //当行展示时调用接口
      if (expandedRows.length) {
        // 展开 将id赋给数组
        that.expands = [];
        if (row) {
          that.expands.push(row.id);
        }
        this.childListLoading = true;
        this.childrenContentisShow = false;
        this.selectManager.managerId = row.id;
        this.selectManager.username = row.username;
        const data = {
          page: 0,
          pageSize: 0,
          managerId: row.id,
        };
        this.getPurchaserList();
      } else {
        // 收起就清空数组id
        that.expands = [];
      }
    },
    getPurchaserList() {
      const data = {
        page: 0,
        pageSize: 0,
        managerId: this.selectManager.managerId,
      };
      getAllPurchasersByPage(data)
        .then((res) => {
          console.log("@@@@childrenData", res.data.purchaserInfos);
          if (res.code === 200) {
            this.childrenPurchaserList = res.data.purchaserInfos;
            this.childrenPurchaserList.push({}); //触发vue更新视图
            this.childrenPurchaserList.pop(); //把最后添加的空对象删除掉
            this.childrenContentisShow = true;
            this.childListLoading = false;
          } else {
            this.childrenPurchaserList = [];
            this.childListLoading = true;
          }
        })
        .catch((err) => {
          this.childrenPurchaserList = [];
          this.childListLoading = false;
        });
    },

    handleSizeChange(val) {
      this.paging.current = 1;
      this.paging.size = val;
      this.getData();
    },
    handleCurrentChange(val) {
      this.paging.current = val;
      this.getData();
    },
    showDialog(row) {
      this.managerInfoVisible = true;
      this.managerInfo = row;
      // console.log(row)
      this.index = 2;
    },
    refreshPassword(accountId) {
      console.log(accountId);
      this.$confirm("将还原该账号密码,此操作不可逆 是否确定?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const result = await resetPassword({ accountId: accountId });
          console.log(result);
          if (result.code === 200) {
            this.$message({
              type: "success",
              message: "还原成功!",
            });
            this.getData();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "操作取消",
          });
        });
    },
    deleteManager(row) {
      this.$confirm("此操作将永久删除这条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const result = await deleteManagerInfo({ id: row.id, accountId : this.$store.getters.accountId });
          console.log(result);
          if (result.code === 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getData();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    organizationSelected(val) {
      this.searchForm.organizeId = val;
      this.search();
    },
    editManagerDialog(row) {
      this.dialogTitle = "编辑管理员信息";
      this.editDialogVisible = true;
      this.managerInfo = this.extendCopy(row);
      this.index = 1;
      console.log(row);
    },
    selectManagerDialog(row) {
      this.dialogTitle = "重新分配管理员";
      this.selectDialogVisible = true;
      let info = this.extendCopy(row);
      this.selectManager.purchaserId = info.id;
      console.log(row);
    },
    // 对象的深拷贝
    // 对象进行深拷贝，否则“编辑”框内修改内容也会影响到页面
    extendCopy(p) {
      var c = {};
      for (var i in p) {
        c[i] = p[i];
      }
      return c;
    },
    addManagerDialog() {
      this.dialogTitle = "添加管理员";
      this.editDialogVisible = true;
      this.index = 0;
    },
    cancel() {
      if (this.index === 2) {
        this.managerInfoVisible = false;
      } else {
        this.editDialogVisible = false;
      }
      this.index = 0;
    },
    cancelSelect() {
      this.selectDialogVisible = false;
    },
    editmanagerInfo(data) {
      // eslint-disable-next-line no-async-promise-executor
      return new Promise(async (resolve, reject) => {
        if (this.index) {
          // 编辑导师信息
          // console.log(val)
          const result = await updateManagerInfo(data);
          // console.log(res)
          if (result.code === 200) {
            this.$message.success("修改成功");
            resolve(result);
          } else {
            this.$message.error("修改失败，请重试");
            reject(result);
          }
        } else {
          const result = await addManagerInfo(data);
          // console.log(res)
          if (result.code === 200) {
            this.$message.success("修改成功");
            resolve(result);
          } else {
            this.$message.error("修改失败，请重试");
            reject(result);
          }
        }
      });
    },
    async ok(val) {
      const response = await this.editmanagerInfo(val);
      console.log(response);
      if (response.code === 200) {
        this.editDialogVisible = false;
        this.getData();
        this.index = 0;
      }
    },
    async reSelect(data) {
      const response = await updatePurchaserManager(data);
      if (response.code === 200) {
        this.selectDialogVisible = false;
        this.getPurchaserList();
      }
    },
    // onSuccess(response, file, fileList) {
    //   console.log(response);
    //   if (response.code !== 200) {
    //     this.$message.error("上传失败，请重试");
    //   } else {
    //     this.$message.success("上传成功");
    //     this.getData();
    //   }
    // },
    // onError(error, file, fileList) {
    //   console.log(error);
    // },
  },
};
</script>
<style lang="scss" scoped>
.el-pagination {
  margin-top: 20px;
  text-align: right;
}
.btn {
  float: right;
  margin-left: 20px;
}
.children-table {
  width: 80%;
  margin-left: 10%;
}
</style>
